import { Router, Request, Response, NextFunction, RequestHandler } from 'express';
import {
    sendMessage,
    getChatHistory,
    getUnreadMessages,
    markAsRead,
    deleteMessage,
    followUser
} from '../controllers/messageController';
import { authenticate } from '../middleware/auth';
import { uploadController } from '../controllers/uploadController';

const router = Router();

// 发送消息
router.post('/', authenticate, async (req: Request, res: Response, next: NextFunction) => {
    try {
        await sendMessage(req, res);
    } catch (error) {
        next(error);
    }
});

// 获取与特定用户的聊天记录
router.get('/chat/:targetUserId', authenticate, (async (req: Request, res: Response, next: NextFunction) => {
    try {
        await getChatHistory(req, res);
    } catch (error) {
        next(error);
    }
}) as RequestHandler);

// 获取未读消息列表
router.get('/unread', authenticate, (async (req: Request, res: Response, next: NextFunction) => {
    try {
        await getUnreadMessages(req, res);
    } catch (error) {
        next(error);
    }
}) as RequestHandler);

// 标记消息为已读
router.put('/read', authenticate, (async (req: Request, res: Response, next: NextFunction) => {
    try {
        await markAsRead(req, res);
    } catch (error) {
        next(error);
    }
}) as RequestHandler);

// 删除消息
router.delete('/:messageId', authenticate, (async (req: Request, res: Response, next: NextFunction) => {
    try {
        await deleteMessage(req, res);
    } catch (error) {
        next(error);
    }
}) as RequestHandler);

// 关注用户
router.post('/follow', authenticate, async (req: Request, res: Response, next: NextFunction) => {
    try {
        await followUser(req, res);
    } catch (error) {
        next(error);
    }
});

router.post('/avatar', async (req: Request, res: Response, next: NextFunction) => {
    try {
        await uploadController.uploadAvatar(req, res);
    } catch (error) {
        next(error);
    }
});

export default router; 